from datetime import datetime             

def calculate_distance(stake1, stake2):
    # 解析桩号格式 Kxxxx+xxx
    def parse_stake(stake):
        km, m = stake.split('+')
        km = int(km[1:])  # 提取千米部分
        m = int(m)        # 提取米部分
        return km, m

    # 解析两个桩号
    km1, m1 = parse_stake(stake1)
    km2, m2 = parse_stake(stake2)

    # 计算两个桩号之间的距离（千米差值 + 米差值）
    distance_km = abs(km1 - km2)
    distance_m = abs(m1 - m2)

    # 如果米差值大于1000，表示跨越了一个千米
    if distance_m >= 1000:
        distance_km += 1
        distance_m -= 1000

    return distance_km, distance_m

# 计算时间差（单位：秒）
def time_difference(timestamp1, timestamp2):
    time_format = "%Y-%m-%dT%H:%M:%S.%f"
    t1 = datetime.strptime(timestamp1, time_format)
    t2 = datetime.strptime(timestamp2, time_format)
    return (t2 - t1).total_seconds()

def kakou_data_process(json_data):

    result = []
    # 提取orgCode和globalFrameNo
    timestamp = json_data.get('timestamp')
    sn = json_data.get('sn')
    # speed = json_data.get('speed')
    licenseCode = json_data.get('plateNumber')
    vehtype = json_data.get('vehicleType')
    laneNum = json_data.get('laneNo')
    # lon = json_data.get('lon')
    # lat = json_data.get('lat')
    row = [timestamp, sn, licenseCode, vehtype, laneNum]
    
    result.append(row)
    return result

def kakou_in_tuunel_data_process(json_data, topic_ip):
    result=[]
    # 提取orgCode和globalFrameNo
    timestamp = json_data.get('externalTrigger').get('timestamp')
    licenseCode = json_data.get('picLicense')
    stake = {150:'TLS_3_1', 154:'TLS_3_2', 158:'TLS_4_1', 162:'TLS_4_2', 166:'TLS_1_1', 169:'TLS_1_2', 172:'TLS_2_1', 175:'TLS_2_2'}
    sn = stake[topic_ip]
    
    vehtype = 0
    laneNum = 0

    row = [timestamp, sn, licenseCode, vehtype, laneNum]
    
    result.append(row)
    return result

def offline_kakou_data_process(json_data):

    result=[]
    # 提取orgCode和globalFrameNo
    timestamp = json_data.get('timestamp')
    sn = json_data.get('sn')
    speed = json_data.get('speed')
    licenseCode = json_data.get('licenseCode')
    vehtype = json_data.get('vehicleType')
    laneNum = json_data.get('laneNo')
    lon = json_data.get('lon')
    lat = json_data.get('lat')
    row = [timestamp, sn, licenseCode, vehtype, laneNum]
    
    result.append(row)
    return result